<?php

use Sc\Util\HtmlElement\El;
use Sc\Util\HtmlStructure\Html\Html;
use Sc\Util\HtmlStructure\Html\Js;
use Sc\Util\HtmlStructure\Html\Js\Axios;
use Sc\Util\HtmlStructure\Html\Js\JsCode;
use Sc\Util\HtmlStructure\Html\Js\JsFor;
use Sc\Util\HtmlStructure\Html\Js\JsFunc;
use Sc\Util\HtmlStructure\Html\Js\JsIf;
use Sc\Util\HtmlStructure\Html\Js\JsVar;

Html::create("Api文档");
Html::loadThemeResource('ElementUI');
Html::css()->load('https://unpkg.com/codemirror@5.65.8/lib/codemirror.css');
Html::css()->load('https://unpkg.com/codemirror@5.65.8/theme/material.css');
Html::css()->load('https://unpkg.com/jsoneditor@10.1.0/dist/jsoneditor.min.css');
Html::js()->load('https://unpkg.com/jsoneditor@10.1.0/dist/jsoneditor.min.js');
Html::js()->load('https://unpkg.com/codemirror@5.65.17/lib/codemirror.js');
Html::js()->load('https://unpkg.com/codemirror@5.65.17/mode/javascript/javascript.js');
Html::js()->load('https://unpkg.com/codemirror@5.65.17/addon/display/autorefresh.js');
Html::css()->addCss(<<<CSS
#scrollbar {
    width: 200px;
    height: calc(100vh - 20px);
}
i.icon{
    color: #E6A23C;
    cursor: pointer;
}
i.cur{
    cursor: pointer;
    font-size: 22px;
    vertical-align: bottom;
}
i.p-icon-all{
    color: #67C23A;
}
b{
    display: inline-block;
    width: 50px;
    text-align: center;
}

.send{
    color: #409EFF;
    position: relative;  
    opacity: 1;  
    transition: transform 0.5s ease, opacity 0.5s ease, filter 0.5s ease;
}
.send:hover{
    transform: translateX(1px); /* 向右移动200px */  
    opacity: 0.5; /* 完全透明 */  
    filter: blur(0px); /* 模糊效果 */ 
}
.el-card{
  height: calc(100vh - 80px);
}
iframe{
    width: 100%;
    height: calc(100vh - 250px);
    border: none;
}
.el-sub-menu__title,.el-sub-menu .el-menu-item{
    height: 35px;
    line-height: 35px;
}
CSS
);


$menu = El::double('el-menu')->setAttrs([
    ':default-active' => 'apiActive',
    ':unique-opened' => 'true',
    'class' => 'menu'
])->append(
    h('template', [ 'v-for'  => '(item, index) in ApiInfo.apiLists',])->append(
        h('el-sub-menu')->setAttrs([
            'v-if'   => "show(item)",
            ':index' => "'p' + index",
        ])->append(
            h('template')->setAttr('#title')->append(
                h('el-icon', [':class' => "{'p-icon-all': item.children.filter(a => starCheck(a)).length == item.children.length}"])
                    ->addClass('icon')
                    ->append('<component :is="item.children.filter(a => starCheck(a)).length > 0 ? \'StarFilled\' : \'Star\'" />'),
                h('span', '{{ item.name }}')
            )
        )->append(
            h('template', [  'v-for'  => '(api, Aindex) in item?.children',])->append(
                h('el-menu-item')->setAttrs([
                    'v-if'   => "show(api, item)",
                    ':index' => "index + '-' + Aindex",
                    '@click' => "selectApi(api, item)"
                ])->append(
                    h('el-icon', ['@click.stop' => 'toggleStar(api)'])
                        ->addClass('icon')
                        ->append('<component :is="starCheck(api) ? \'StarFilled\' : \'Star\'">'),
                    h('template')->setAttr('#title')->append(
                        h('span')->setAttr('v-if', 'api.version.filter(v => v < 0).length <= 0')->append('{{ api.name }}'),
                        h('span')->setAttr('v-else')->addClass('re-del')->append('{{ api.name }}')
                    )
                )
            )
        )
    )
);

$vue  = Html::js()->vue;

$vue->set('GET', 'GET');
$vue->set('showStar', null);
$vue->set('Stars', []);
$vue->set('loading', false);
$vue->set('searchText', '');
$vue->set('showVersion', (int)\App\Util\Helper::request()->query('version', 1));
$vue->set('apiActive', null);
$vue->set('showApiInfo', 'Form');
$vue->set('showParamInfo', 'response');
$vue->set('response', "@{}");
$vue->set('responseEditor', null);
$vue->set('currentApiInfo', null);
$vue->set('currentGroupName', null);
$vue->set('apiFormData', null);
$vue->set('apiFormEditor', null);
$vue->set('ApiInfo', "@{apiLists:[]}");


$vue->event('created', JsCode::make(
    JsCode::raw('this.getApiInfo()'),
    JsIf::when('localStorage.getItem("stars")')->then(
        JsVar::set('this.Stars', '@JSON.parse(localStorage.getItem("stars"))'),
        Js::log("@this.Stars")
    ),
));
$vue->event('mounted', JsCode::make(
    JsCode::raw("ElementPlus.ElNotification({
    duration: 0,
    title: '提示',
    dangerouslyUseHTMLString: true,
    message: `<p>响应状态码说明：</p>
         <p>200:成功</p>
         <p>202:常规错误</p>
         <p>1001:token 过期，并返回了新的token</p>
         <p>1002:token 无效</p>
         <br>
         <p>token携带方式可查看测试js请求脚本</p>
         <br>
         <p>标记、收藏说明：</p>
         <p>标记、收藏为本地存储，下次打开页面会自动恢复，接口版本更新时会清除标记效果</p>
         <br>
         <p>接口测试请求说明：</p>
         <p>登录返回的token会自动保存本地，下次请求会自动带上，刷新时也会自动更新，重新请求即可</p>
        `,
    type: 'warning'
  });")
));

$vue->addMethod('starCheck', ['api'], JsCode::raw("return this.Stars[api.url] >= api.version.length"));


$vue->addMethod("toggleStar", JsFunc::anonymous(['api'])->code(
    JsIf::when("this.starCheck(api)")->then(
        JsCode::raw('delete this.Stars[api.url]'),
        JsCode::raw('this.$message.success("已取消收藏")')
    )->else(
        JsCode::raw("this.Stars[api.url] = api.version.length"),
        JsCode::raw('this.$message.success("已收藏")')
    ),
    JsCode::raw('localStorage.setItem("stars", JSON.stringify({...this.Stars}))')
));

$vue->addMethod('selectApi', JsFunc::anonymous(['api', 'group'])->code(
    JsVar::set('this.currentApiInfo', '@api'),
    JsVar::set('this.currentGroupName', '@group.name'),
    JsVar::set('this.apiFormData', '@this.paramsResolve(api.requestParams)'),
    JsCode::raw("this.apiFormEditor && this.apiFormEditor.set(this.apiFormData)"),
    JsCode::raw("this.responseEditor && this.responseEditor.set(null)"),
    JsCode::raw("this.showApiInfo = 'Form'"),
));

$vue->addMethod('paramsResolve', JsFunc::anonymous(['params'])->code(
    JsVar::def('form', '@{}'),
    JsFor::loop('let i = 0; i < params.length; i++')->then(
        JsIf::when("params[i].type === 'Array'")->then(
            JsIf::when("params[i].children.length > 0")->then(
                JsVar::set('form[params[i].name]', "@[this.paramsResolve(params[i].children)]")
            )->else(
                JsVar::set('form[params[i].name]', "@[]")
            )
        )->elseIf("params[i].type === 'Object'")->then(
            JsVar::set('form[params[i].name]', "@this.paramsResolve(params[i].children)")
        )->elseIf("params[i].type === 'Integer' || params[i].type === 'Float'")->then(
            JsIf::when("params[i].name === 'page'")->then(
                JsVar::set('form[params[i].name]', 1)
            )->elseIf("params[i].name === 'pageSize' || params[i].name === 'limit'")->then(
                JsVar::set('form[params[i].name]', 10)
            )->else(
                JsVar::set('form[params[i].name]', 0)
            ),
        )->elseIf("params[i].type === 'File'")->then(
            JsVar::set("form[params[i]]", null)
        )->else(
            JsVar::set('form[params[i].name]', "")
        )
    ),
    JsCode::raw('return form')
));

return h('div')->setAttr('style', 'display: flex;')->append(
    h('el-scrollbar')->setId('scrollbar')->append($menu),
    h('el-row')->setAttr('style', 'flex:1;margin-left: 10px;')->setAttr(':gutter', 5)->append(
        h('el-col')->setAttr(':span', '24')->append(include __DIR__ . '/view_filter.php'),
        h('el-col')->setAttr(':span', '12')->append(include __DIR__ . '/view_api_info.php'),
        h('el-col')->setAttr(':span', '12')->append(include __DIR__ . '/view_param.php'),
    )
);